package util;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class RequestUtil {

	@SuppressWarnings("unchecked")
	public static Map<String, String> transferMap(HttpServletRequest request) {
		Map<String, String> paramMap = new HashMap<String, String>();
		Map<String, String[]> requestMap = request.getParameterMap();
		for (Map.Entry<String, String[]> e : requestMap.entrySet()) {
			if (e.getKey() != null && e.getValue() != null) {
				if (e.getValue().length == 1) {
					paramMap.put(e.getKey(), e.getValue()[0]);
				} else {
					String[] values = e.getValue();
					String value = "";
					for (int i = 0; i < values.length; i++) {
						value = values[i] + ",";
					}
					value = value.substring(0, value.length() - 1);
					paramMap.put(e.getKey(), value);
				}
			}
		}
		return paramMap;
	}

	@SuppressWarnings("unchecked")
	public static String transferString(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer();
		Map<String, String[]> requestMap = request.getParameterMap();
		for (Map.Entry<String, String[]> e : requestMap.entrySet()) {
			if (e.getKey() != null && e.getValue() != null) {
				try {
					if (e.getValue().length == 1) {
						sb.append(e.getKey() + "=" + URLEncoder.encode(e.getValue()[0], "UTF-8") + "&");
					} else {
						String[] values = e.getValue();
						String value = "";
						for (int i = 0; i < values.length; i++) {
							value = values[i] + ",";
						}
						value = value.substring(0, value.length() - 1);
						sb.append(e.getKey() + "=" + URLEncoder.encode(value, "UTF-8") + "&");
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
}
